{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "661a425f-9032-46c6-8458-7e4328653d40",
   "metadata": {},
   "source": [
    "# Query Pipeline for Advanced Text-to-SQL \n",
    "\n",
    "In this guide we show you how to setup a text-to-SQL pipeline over your data with our [query pipeline](https://docs.llamaindex.ai/en/stable/module_guides/querying/pipeline/root.html) syntax.\n",
    "\n",
    "This gives you flexibility to enhance text-to-SQL with additional techniques. We show these in the below sections: \n",
    "1. **Query-Time Table Retrieval**: Dynamically retrieve relevant tables in the text-to-SQL prompt.\n",
    "2. **Query-Time Sample Row retrieval**: Embed/Index each row, and dynamically retrieve example rows for each table in the text-to-SQL prompt.\n",
    "\n",
    "Our out-of-the box pipelines include our `NLSQLTableQueryEngine` and `SQLTableRetrieverQueryEngine`. (if you want to check out our text-to-SQL guide using these modules, take a look [here](https://docs.llamaindex.ai/en/stable/examples/index_structs/struct_indices/SQLIndexDemo.html)). This guide implements an advanced version of those modules, giving you the utmost flexibility to apply this to your own setting."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9395ad03-1aea-4ce1-9457-51e2fd86f88a",
   "metadata": {},
   "source": [
    "## Load and Ingest Data\n",
    "\n",
    "\n",
    "### Load Data\n",
    "We use the [WikiTableQuestions dataset](https://ppasupat.github.io/WikiTableQuestions/) (Pasupat and Liang 2015) as our test dataset.\n",
    "\n",
    "We go through all the csv's in one folder, store each in a sqlite database (we will then build an object index over each table schema)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "45d9c316",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install llama-index-llms-openai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "02212d47-080f-405b-abb0-1eccc2b286c7",
   "metadata": {},
   "outputs": [],
   "source": [
    "!wget \"https://github.com/ppasupat/WikiTableQuestions/releases/download/v1.0.2/WikiTableQuestions-1.0.2-compact.zip\" -O data.zip\n",
    "!unzip data.zip"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "52e9e6e2-86b8-4c29-af41-8c935c02a45a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from pathlib import Path\n",
    "\n",
    "data_dir = Path(\"./WikiTableQuestions/csv/200-csv\")\n",
    "csv_files = sorted([f for f in data_dir.glob(\"*.csv\")])\n",
    "dfs = []\n",
    "for csv_file in csv_files:\n",
    "    print(f\"processing file: {csv_file}\")\n",
    "    try:\n",
    "        df = pd.read_csv(csv_file)\n",
    "        dfs.append(df)\n",
    "    except Exception as e:\n",
    "        print(f\"Error parsing {csv_file}: {str(e)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c653683-0d9b-49b7-9ed3-800e77a322a6",
   "metadata": {},
   "source": [
    "### Extract Table Name and Summary from each Table\n",
    "\n",
    "Here we use gpt-3.5 to extract a table name (with underscores) and summary from each table with our Pydantic program."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ea271a12-1ce3-476e-bf7c-f8f3a27affe9",
   "metadata": {},
   "outputs": [],
   "source": [
    "tableinfo_dir = \"WikiTableQuestions_TableInfo\"\n",
    "!mkdir {tableinfo_dir}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a5915db4-34fe-42a2-91e9-0f38db4cdb1f",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.program import LLMTextCompletionProgram\n",
    "from llama_index.core.bridge.pydantic import BaseModel, Field\n",
    "from llama_index.llms.openai import OpenAI\n",
    "\n",
    "\n",
    "class TableInfo(BaseModel):\n",
    "    \"\"\"Information regarding a structured table.\"\"\"\n",
    "\n",
    "    table_name: str = Field(\n",
    "        ..., description=\"table name (must be underscores and NO spaces)\"\n",
    "    )\n",
    "    table_summary: str = Field(\n",
    "        ..., description=\"short, concise summary/caption of the table\"\n",
    "    )\n",
    "\n",
    "\n",
    "prompt_str = \"\"\"\\\n",
    "Give me a summary of the table with the following JSON format.\n",
    "\n",
    "- The table name must be unique to the table and describe it while being concise. \n",
    "- Do NOT output a generic table name (e.g. table, my_table).\n",
    "\n",
    "Do NOT make the table name one of the following: {exclude_table_name_list}\n",
    "\n",
    "Table:\n",
    "{table_str}\n",
    "\n",
    "Summary: \"\"\"\n",
    "\n",
    "program = LLMTextCompletionProgram.from_defaults(\n",
    "    output_cls=TableInfo,\n",
    "    llm=OpenAI(model=\"gpt-3.5-turbo\"),\n",
    "    prompt_template_str=prompt_str,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4734e3d2-7602-4584-b6b8-499ca8bc825c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "\n",
    "def _get_tableinfo_with_index(idx: int) -> str:\n",
    "    results_gen = Path(tableinfo_dir).glob(f\"{idx}_*\")\n",
    "    results_list = list(results_gen)\n",
    "    if len(results_list) == 0:\n",
    "        return None\n",
    "    elif len(results_list) == 1:\n",
    "        path = results_list[0]\n",
    "        return TableInfo.parse_file(path)\n",
    "    else:\n",
    "        raise ValueError(\n",
    "            f\"More than one file matching index: {list(results_gen)}\"\n",
    "        )\n",
    "\n",
    "\n",
    "table_names = set()\n",
    "table_infos = []\n",
    "for idx, df in enumerate(dfs):\n",
    "    table_info = _get_tableinfo_with_index(idx)\n",
    "    if table_info:\n",
    "        table_infos.append(table_info)\n",
    "    else:\n",
    "        while True:\n",
    "            df_str = df.head(10).to_csv()\n",
    "            table_info = program(\n",
    "                table_str=df_str,\n",
    "                exclude_table_name_list=str(list(table_names)),\n",
    "            )\n",
    "            table_name = table_info.table_name\n",
    "            print(f\"Processed table: {table_name}\")\n",
    "            if table_name not in table_names:\n",
    "                table_names.add(table_name)\n",
    "                break\n",
    "            else:\n",
    "                # try again\n",
    "                print(f\"Table name {table_name} already exists, trying again.\")\n",
    "                pass\n",
    "\n",
    "        out_file = f\"{tableinfo_dir}/{idx}_{table_name}.json\"\n",
    "        json.dump(table_info.dict(), open(out_file, \"w\"))\n",
    "    table_infos.append(table_info)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "64ac4df7-434c-422b-84b2-368e2dc27491",
   "metadata": {},
   "source": [
    "### Put Data in SQL Database\n",
    "\n",
    "We use `sqlalchemy`, a popular SQL database toolkit, to load all the tables."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1d84718a-5b6d-4c13-b984-360082b91d73",
   "metadata": {},
   "outputs": [],
   "source": [
    "# put data into sqlite db\n",
    "from sqlalchemy import (\n",
    "    create_engine,\n",
    "    MetaData,\n",
    "    Table,\n",
    "    Column,\n",
    "    String,\n",
    "    Integer,\n",
    ")\n",
    "import re\n",
    "\n",
    "\n",
    "# Function to create a sanitized column name\n",
    "def sanitize_column_name(col_name):\n",
    "    # Remove special characters and replace spaces with underscores\n",
    "    return re.sub(r\"\\W+\", \"_\", col_name)\n",
    "\n",
    "\n",
    "# Function to create a table from a DataFrame using SQLAlchemy\n",
    "def create_table_from_dataframe(\n",
    "    df: pd.DataFrame, table_name: str, engine, metadata_obj\n",
    "):\n",
    "    # Sanitize column names\n",
    "    sanitized_columns = {col: sanitize_column_name(col) for col in df.columns}\n",
    "    df = df.rename(columns=sanitized_columns)\n",
    "\n",
    "    # Dynamically create columns based on DataFrame columns and data types\n",
    "    columns = [\n",
    "        Column(col, String if dtype == \"object\" else Integer)\n",
    "        for col, dtype in zip(df.columns, df.dtypes)\n",
    "    ]\n",
    "\n",
    "    # Create a table with the defined columns\n",
    "    table = Table(table_name, metadata_obj, *columns)\n",
    "\n",
    "    # Create the table in the database\n",
    "    metadata_obj.create_all(engine)\n",
    "\n",
    "    # Insert data from DataFrame into the table\n",
    "    with engine.connect() as conn:\n",
    "        for _, row in df.iterrows():\n",
    "            insert_stmt = table.insert().values(**row.to_dict())\n",
    "            conn.execute(insert_stmt)\n",
    "        conn.commit()\n",
    "\n",
    "\n",
    "engine = create_engine(\"sqlite:///:memory:\")\n",
    "metadata_obj = MetaData()\n",
    "for idx, df in enumerate(dfs):\n",
    "    tableinfo = _get_tableinfo_with_index(idx)\n",
    "    print(f\"Creating table: {tableinfo.table_name}\")\n",
    "    create_table_from_dataframe(df, tableinfo.table_name, engine, metadata_obj)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7b8ea367-93d1-4399-94fe-78ed92e25de4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "🌍 To view the Phoenix app in your browser, visit http://127.0.0.1:6006/\n",
      "📺 To view the Phoenix app in a notebook, run `px.active_session().view()`\n",
      "📖 For more information on how to use Phoenix, check out https://docs.arize.com/phoenix\n"
     ]
    }
   ],
   "source": [
    "# setup Arize Phoenix for logging/observability\n",
    "import phoenix as px\n",
    "import llama_index.core\n",
    "\n",
    "px.launch_app()\n",
    "llama_index.core.set_global_handler(\"arize_phoenix\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4b0b0de3-58a8-429b-a8b0-7a112028725c",
   "metadata": {},
   "source": [
    "## Advanced Capability 1: Text-to-SQL with Query-Time Table Retrieval.\n",
    "\n",
    "We now show you how to setup an e2e text-to-SQL with table retrieval.\n",
    "\n",
    "### Define Modules\n",
    "\n",
    "Here we define the core modules.\n",
    "1. Object index + retriever to store table schemas\n",
    "2. SQLDatabase object to connect to the above tables + SQLRetriever.\n",
    "3. Text-to-SQL Prompt\n",
    "4. Response synthesis Prompt\n",
    "5. LLM"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d350c9b2-ff4e-4714-841d-bce1a8ff28b2",
   "metadata": {},
   "source": [
    "Object index, retriever, SQLDatabase"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e240f48d-4458-4a66-b4fc-a5b5b8535353",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.objects import (\n",
    "    SQLTableNodeMapping,\n",
    "    ObjectIndex,\n",
    "    SQLTableSchema,\n",
    ")\n",
    "from llama_index.core import SQLDatabase, VectorStoreIndex\n",
    "\n",
    "sql_database = SQLDatabase(engine)\n",
    "\n",
    "table_node_mapping = SQLTableNodeMapping(sql_database)\n",
    "table_schema_objs = [\n",
    "    SQLTableSchema(table_name=t.table_name, context_str=t.table_summary)\n",
    "    for t in table_infos\n",
    "]  # add a SQLTableSchema for each table\n",
    "\n",
    "obj_index = ObjectIndex.from_objects(\n",
    "    table_schema_objs,\n",
    "    table_node_mapping,\n",
    "    VectorStoreIndex,\n",
    ")\n",
    "obj_retriever = obj_index.as_retriever(similarity_top_k=3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3a793d6b-762c-492d-a929-c77c1bffcf0e",
   "metadata": {},
   "source": [
    "SQLRetriever + Table Parser"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "97371260-5ae3-4c93-9ff0-3c4fed3d5b53",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.retrievers import SQLRetriever\n",
    "from typing import List\n",
    "from llama_index.core.query_pipeline import FnComponent\n",
    "\n",
    "sql_retriever = SQLRetriever(sql_database)\n",
    "\n",
    "\n",
    "def get_table_context_str(table_schema_objs: List[SQLTableSchema]):\n",
    "    \"\"\"Get table context string.\"\"\"\n",
    "    context_strs = []\n",
    "    for table_schema_obj in table_schema_objs:\n",
    "        table_info = sql_database.get_single_table_info(\n",
    "            table_schema_obj.table_name\n",
    "        )\n",
    "        if table_schema_obj.context_str:\n",
    "            table_opt_context = \" The table description is: \"\n",
    "            table_opt_context += table_schema_obj.context_str\n",
    "            table_info += table_opt_context\n",
    "\n",
    "        context_strs.append(table_info)\n",
    "    return \"\\n\\n\".join(context_strs)\n",
    "\n",
    "\n",
    "table_parser_component = FnComponent(fn=get_table_context_str)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1c88c000-5f30-4d8d-bfa6-c9551b1fdbae",
   "metadata": {},
   "source": [
    "Text-to-SQL Prompt + Output Parser"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2ebb0d0d-4a13-45d2-9e59-62dbb3cd101f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Given an input question, first create a syntactically correct {dialect} query to run, then look at the results of the query and return the answer. You can order the results by a relevant column to return the most interesting examples in the database.\n",
      "\n",
      "Never query for all the columns from a specific table, only ask for a few relevant columns given the question.\n",
      "\n",
      "Pay attention to use only the column names that you can see in the schema description. Be careful to not query for columns that do not exist. Pay attention to which column is in which table. Also, qualify column names with the table name when needed. You are required to use the following format, each taking one line:\n",
      "\n",
      "Question: Question here\n",
      "SQLQuery: SQL Query to run\n",
      "SQLResult: Result of the SQLQuery\n",
      "Answer: Final answer here\n",
      "\n",
      "Only use tables listed below.\n",
      "{schema}\n",
      "\n",
      "Question: {query_str}\n",
      "SQLQuery: \n"
     ]
    }
   ],
   "source": [
    "from llama_index.core.prompts.default_prompts import DEFAULT_TEXT_TO_SQL_PROMPT\n",
    "from llama_index.core import PromptTemplate\n",
    "from llama_index.core.query_pipeline import FnComponent\n",
    "from llama_index.core.llms import ChatResponse\n",
    "\n",
    "\n",
    "def parse_response_to_sql(response: ChatResponse) -> str:\n",
    "    \"\"\"Parse response to SQL.\"\"\"\n",
    "    response = response.message.content\n",
    "    sql_query_start = response.find(\"SQLQuery:\")\n",
    "    if sql_query_start != -1:\n",
    "        response = response[sql_query_start:]\n",
    "        # TODO: move to removeprefix after Python 3.9+\n",
    "        if response.startswith(\"SQLQuery:\"):\n",
    "            response = response[len(\"SQLQuery:\") :]\n",
    "    sql_result_start = response.find(\"SQLResult:\")\n",
    "    if sql_result_start != -1:\n",
    "        response = response[:sql_result_start]\n",
    "    return response.strip().strip(\"```\").strip()\n",
    "\n",
    "\n",
    "sql_parser_component = FnComponent(fn=parse_response_to_sql)\n",
    "\n",
    "text2sql_prompt = DEFAULT_TEXT_TO_SQL_PROMPT.partial_format(\n",
    "    dialect=engine.dialect.name\n",
    ")\n",
    "print(text2sql_prompt.template)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "55e9799c-eb29-4bcf-92dd-fb75d18a2f46",
   "metadata": {},
   "source": [
    "Response Synthesis Prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e9ae7166-4cac-4819-950e-9bd445cf737d",
   "metadata": {},
   "outputs": [],
   "source": [
    "response_synthesis_prompt_str = (\n",
    "    \"Given an input question, synthesize a response from the query results.\\n\"\n",
    "    \"Query: {query_str}\\n\"\n",
    "    \"SQL: {sql_query}\\n\"\n",
    "    \"SQL Response: {context_str}\\n\"\n",
    "    \"Response: \"\n",
    ")\n",
    "response_synthesis_prompt = PromptTemplate(\n",
    "    response_synthesis_prompt_str,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1969aa70-6f5d-4905-bb22-f11db20e9653",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm = OpenAI(model=\"gpt-3.5-turbo\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6fda98f0-376a-4192-85b6-d9ba93082139",
   "metadata": {},
   "source": [
    "### Define Query Pipeline\n",
    "\n",
    "Now that the components are in place, let's define the query pipeline! "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "de6f9b80-2759-429b-937f-796569390769",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.query_pipeline import (\n",
    "    QueryPipeline as QP,\n",
    "    Link,\n",
    "    InputComponent,\n",
    "    CustomQueryComponent,\n",
    ")\n",
    "\n",
    "qp = QP(\n",
    "    modules={\n",
    "        \"input\": InputComponent(),\n",
    "        \"table_retriever\": obj_retriever,\n",
    "        \"table_output_parser\": table_parser_component,\n",
    "        \"text2sql_prompt\": text2sql_prompt,\n",
    "        \"text2sql_llm\": llm,\n",
    "        \"sql_output_parser\": sql_parser_component,\n",
    "        \"sql_retriever\": sql_retriever,\n",
    "        \"response_synthesis_prompt\": response_synthesis_prompt,\n",
    "        \"response_synthesis_llm\": llm,\n",
    "    },\n",
    "    verbose=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4dffe6d9-fe05-43d5-915a-ace406c96164",
   "metadata": {},
   "outputs": [],
   "source": [
    "qp.add_chain([\"input\", \"table_retriever\", \"table_output_parser\"])\n",
    "qp.add_link(\"input\", \"text2sql_prompt\", dest_key=\"query_str\")\n",
    "qp.add_link(\"table_output_parser\", \"text2sql_prompt\", dest_key=\"schema\")\n",
    "qp.add_chain(\n",
    "    [\"text2sql_prompt\", \"text2sql_llm\", \"sql_output_parser\", \"sql_retriever\"]\n",
    ")\n",
    "qp.add_link(\n",
    "    \"sql_output_parser\", \"response_synthesis_prompt\", dest_key=\"sql_query\"\n",
    ")\n",
    "qp.add_link(\n",
    "    \"sql_retriever\", \"response_synthesis_prompt\", dest_key=\"context_str\"\n",
    ")\n",
    "qp.add_link(\"input\", \"response_synthesis_prompt\", dest_key=\"query_str\")\n",
    "qp.add_link(\"response_synthesis_prompt\", \"response_synthesis_llm\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "84f3dba6-b7bd-4252-b19b-b42a9e9fb71e",
   "metadata": {},
   "source": [
    "### Visualize Query Pipeline\n",
    "\n",
    "A really nice property of the query pipeline syntax is you can easily visualize it in a graph via networkx."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4856d77a-09ed-4509-baed-5443a29b71c1",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pyvis.network import Network\n",
    "\n",
    "net = Network(notebook=True, cdn_resources=\"in_line\", directed=True)\n",
    "net.from_nx(qp.dag)\n",
    "net.show(\"text2sql_dag.html\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c947303-9e09-47eb-a73e-52d82e83251a",
   "metadata": {},
   "source": [
    "### Run Some Queries! \n",
    "\n",
    "Now we're ready to run some queries across this entire pipeline."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f1a761d1-8658-475e-b4b3-cc0fcb194e2e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1;3;38;2;155;135;227m> Running module input with input: \n",
      "query: What was the year that The Notorious B.I.G was signed to Bad Boy?\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module table_retriever with input: \n",
      "input: What was the year that The Notorious B.I.G was signed to Bad Boy?\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module table_output_parser with input: \n",
      "table_schema_objs: [SQLTableSchema(table_name='Bad_Boy_Artists', context_str='List of artists signed to Bad Boy Records and their album releases'), SQLTableSchema(table_name='Bad_Boy_Artists', context_str='List of artis...\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module text2sql_prompt with input: \n",
      "query_str: What was the year that The Notorious B.I.G was signed to Bad Boy?\n",
      "schema: Table 'Bad_Boy_Artists' has columns: Act (VARCHAR), Year_signed (INTEGER), _Albums_released_under_Bad_Boy (VARCHAR), and foreign keys: . The table description is: List of artists signed to Bad Boy Rec...\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module text2sql_llm with input: \n",
      "messages: Given an input question, first create a syntactically correct sqlite query to run, then look at the results of the query and return the answer. You can order the results by a relevant column to return...\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module sql_output_parser with input: \n",
      "response: assistant: SELECT Year_signed\n",
      "FROM Bad_Boy_Artists\n",
      "WHERE Act = 'The Notorious B.I.G'\n",
      "SQLResult: 1993\n",
      "Answer: The Notorious B.I.G was signed to Bad Boy in 1993.\n",
      "\n",
      "\u001b[0mRAW RESPONSE  SELECT Year_signed\n",
      "FROM Bad_Boy_Artists\n",
      "WHERE Act = 'The Notorious B.I.G'\n",
      "SQLResult: 1993\n",
      "Answer: The Notorious B.I.G was signed to Bad Boy in 1993.\n",
      "\u001b[1;3;38;2;155;135;227m> Running module sql_retriever with input: \n",
      "input: SELECT Year_signed\n",
      "FROM Bad_Boy_Artists\n",
      "WHERE Act = 'The Notorious B.I.G'\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module response_synthesis_prompt with input: \n",
      "query_str: What was the year that The Notorious B.I.G was signed to Bad Boy?\n",
      "sql_query: SELECT Year_signed\n",
      "FROM Bad_Boy_Artists\n",
      "WHERE Act = 'The Notorious B.I.G'\n",
      "context_str: [NodeWithScore(node=TextNode(id_='4ae2f8fc-b803-4238-8433-7a431c2df391', embedding=None, metadata={}, excluded_embed_metadata_keys=[], excluded_llm_metadata_keys=[], relationships={}, hash='c336a1cbf9...\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module response_synthesis_llm with input: \n",
      "messages: Given an input question, synthesize a response from the query results.\n",
      "Query: What was the year that The Notorious B.I.G was signed to Bad Boy?\n",
      "SQL: SELECT Year_signed\n",
      "FROM Bad_Boy_Artists\n",
      "WHERE Act =...\n",
      "\n",
      "\u001b[0massistant: The Notorious B.I.G was signed to Bad Boy in 1993.\n"
     ]
    }
   ],
   "source": [
    "response = qp.run(\n",
    "    query=\"What was the year that The Notorious B.I.G was signed to Bad Boy?\"\n",
    ")\n",
    "print(str(response))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "958e05c5-b2fa-4e26-bd60-0cea587e2c73",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1;3;38;2;155;135;227m> Running module input with input: \n",
      "query: Who won best directory in the 1972 academy awards\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module table_retriever with input: \n",
      "input: Who won best directory in the 1972 academy awards\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module table_output_parser with input: \n",
      "table_schema_objs: [SQLTableSchema(table_name='Academy_Awards_1972', context_str='List of award categories and nominees for the 1972 Academy Awards'), SQLTableSchema(table_name='Academy_Awards_1972', context_str='List o...\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module text2sql_prompt with input: \n",
      "query_str: Who won best directory in the 1972 academy awards\n",
      "schema: Table 'Academy_Awards_1972' has columns: Award (VARCHAR), Category (VARCHAR), Nominee (VARCHAR), Result (VARCHAR), and foreign keys: . The table description is: List of award categories and nominees f...\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module text2sql_llm with input: \n",
      "messages: Given an input question, first create a syntactically correct sqlite query to run, then look at the results of the query and return the answer. You can order the results by a relevant column to return...\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module sql_output_parser with input: \n",
      "response: assistant: SELECT Nominee\n",
      "FROM Academy_Awards_1972\n",
      "WHERE Category = 'Best Director' AND Result = 'Won'\n",
      "SQLResult: The result of the SQLQuery will be the name of the director who won the Best Director ...\n",
      "\n",
      "\u001b[0mRAW RESPONSE  SELECT Nominee\n",
      "FROM Academy_Awards_1972\n",
      "WHERE Category = 'Best Director' AND Result = 'Won'\n",
      "SQLResult: The result of the SQLQuery will be the name of the director who won the Best Director award in the 1972 Academy Awards.\n",
      "Answer: The winner of the Best Director award in the 1972 Academy Awards was [Director's Name].\n",
      "\u001b[1;3;38;2;155;135;227m> Running module sql_retriever with input: \n",
      "input: SELECT Nominee\n",
      "FROM Academy_Awards_1972\n",
      "WHERE Category = 'Best Director' AND Result = 'Won'\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module response_synthesis_prompt with input: \n",
      "query_str: Who won best directory in the 1972 academy awards\n",
      "sql_query: SELECT Nominee\n",
      "FROM Academy_Awards_1972\n",
      "WHERE Category = 'Best Director' AND Result = 'Won'\n",
      "context_str: [NodeWithScore(node=TextNode(id_='2ebd2cb3-7836-4f93-9898-4c0798da4a41', embedding=None, metadata={}, excluded_embed_metadata_keys=[], excluded_llm_metadata_keys=[], relationships={}, hash='a74ca5f33c...\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module response_synthesis_llm with input: \n",
      "messages: Given an input question, synthesize a response from the query results.\n",
      "Query: Who won best directory in the 1972 academy awards\n",
      "SQL: SELECT Nominee\n",
      "FROM Academy_Awards_1972\n",
      "WHERE Category = 'Best Dire...\n",
      "\n",
      "\u001b[0massistant: The winner for Best Director in the 1972 Academy Awards was William Friedkin.\n"
     ]
    }
   ],
   "source": [
    "response = qp.run(query=\"Who won best director in the 1972 academy awards\")\n",
    "print(str(response))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "529461e1-5ffd-41e6-8310-12c5559e1962",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1;3;38;2;155;135;227m> Running module input with input: \n",
      "query: What was the term of Pasquale Preziosa?\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module table_retriever with input: \n",
      "input: What was the term of Pasquale Preziosa?\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module table_output_parser with input: \n",
      "table_schema_objs: [SQLTableSchema(table_name='Italian_Presidents', context_str='List of Italian Presidents and their terms in office'), SQLTableSchema(table_name='Italian_Presidents', context_str='List of Italian Presi...\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module text2sql_prompt with input: \n",
      "query_str: What was the term of Pasquale Preziosa?\n",
      "schema: Table 'Italian_Presidents' has columns: Name (VARCHAR), Term_start (VARCHAR), Term_end (VARCHAR), and foreign keys: . The table description is: List of Italian Presidents and their terms in office\n",
      "\n",
      "Ta...\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module text2sql_llm with input: \n",
      "messages: Given an input question, first create a syntactically correct sqlite query to run, then look at the results of the query and return the answer. You can order the results by a relevant column to return...\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module sql_output_parser with input: \n",
      "response: assistant: SELECT Term_start, Term_end\n",
      "FROM Italian_Presidents\n",
      "WHERE Name = 'Pasquale Preziosa'\n",
      "SQLResult: Term_start = '2006-05-18', Term_end = '2006-05-22'\n",
      "Answer: Pasquale Preziosa's term was from ...\n",
      "\n",
      "\u001b[0mRAW RESPONSE  SELECT Term_start, Term_end\n",
      "FROM Italian_Presidents\n",
      "WHERE Name = 'Pasquale Preziosa'\n",
      "SQLResult: Term_start = '2006-05-18', Term_end = '2006-05-22'\n",
      "Answer: Pasquale Preziosa's term was from May 18, 2006 to May 22, 2006.\n",
      "\u001b[1;3;38;2;155;135;227m> Running module sql_retriever with input: \n",
      "input: SELECT Term_start, Term_end\n",
      "FROM Italian_Presidents\n",
      "WHERE Name = 'Pasquale Preziosa'\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module response_synthesis_prompt with input: \n",
      "query_str: What was the term of Pasquale Preziosa?\n",
      "sql_query: SELECT Term_start, Term_end\n",
      "FROM Italian_Presidents\n",
      "WHERE Name = 'Pasquale Preziosa'\n",
      "context_str: [NodeWithScore(node=TextNode(id_='75dfe777-3186-4a57-8969-9e33fb8ab41a', embedding=None, metadata={}, excluded_embed_metadata_keys=[], excluded_llm_metadata_keys=[], relationships={}, hash='99f2d91e91...\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module response_synthesis_llm with input: \n",
      "messages: Given an input question, synthesize a response from the query results.\n",
      "Query: What was the term of Pasquale Preziosa?\n",
      "SQL: SELECT Term_start, Term_end\n",
      "FROM Italian_Presidents\n",
      "WHERE Name = 'Pasquale Pr...\n",
      "\n",
      "\u001b[0massistant: Pasquale Preziosa's term started on 25 February 2013 and he is currently the incumbent.\n"
     ]
    }
   ],
   "source": [
    "response = qp.run(query=\"What was the term of Pasquale Preziosa?\")\n",
    "print(str(response))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9f14e889-7937-48ed-98c1-99dd570b3fe1",
   "metadata": {},
   "source": [
    "## 2. Advanced Capability 2: Text-to-SQL with Query-Time Row Retrieval (along with Table Retrieval)\n",
    "\n",
    "One problem in the previous example is that if the user asks a query that asks for \"The Notorious BIG\" but the artist is stored as \"The Notorious B.I.G\", then the generated SELECT statement will likely not return any matches.\n",
    "\n",
    "We can alleviate this problem by fetching a small number of example rows per table. A naive option would be to just take the first k rows. Instead, we embed, index, and retrieve k relevant rows given the user query to give the text-to-SQL LLM the most contextually relevant information for SQL generation.\n",
    "\n",
    "We now extend our query pipeline."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "203c7148-ae2e-4c9a-a6c1-f9017041a48b",
   "metadata": {},
   "source": [
    "### Index Each Table\n",
    "\n",
    "We embed/index the rows of each table, resulting in one index per table."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "250b7408-6525-4b2b-aaa0-d0448e97a25a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Indexing rows in table: Academy_Awards_1972\n",
      "Indexing rows in table: Actress_Awards\n",
      "Indexing rows in table: Actress_Awards_Table\n",
      "Indexing rows in table: Actress_Filmography\n",
      "Indexing rows in table: Afrikaans_Language_Translations\n",
      "Indexing rows in table: Airport_Information\n",
      "Indexing rows in table: Average_Temperature_Precipitation\n",
      "Indexing rows in table: Average_Temperature_and_Precipitation\n",
      "Indexing rows in table: BBC_Radio_Costs\n",
      "Indexing rows in table: Bad_Boy_Artists\n",
      "Indexing rows in table: Boxing_Matches\n",
      "Indexing rows in table: Club_Performance_Norway\n",
      "Indexing rows in table: Disappeared_Persons\n",
      "Indexing rows in table: Drop Events\n",
      "Indexing rows in table: European_Football_Standings\n",
      "Indexing rows in table: Football_Team_Records\n",
      "Indexing rows in table: Gortynia_Municipalities\n",
      "Indexing rows in table: Grammy_Awards\n",
      "Indexing rows in table: Italian_Presidents\n",
      "Indexing rows in table: Kentucky_Derby_Winners\n",
      "Indexing rows in table: Kinase_Cancer_Relationships\n",
      "Indexing rows in table: Kodachrome_Film\n",
      "Indexing rows in table: New_Mexico_Officials\n",
      "Indexing rows in table: Number_Encoding_Probability\n",
      "Indexing rows in table: Peak_Chart_Positions\n",
      "Indexing rows in table: Political Positions of Lord Beaverbrook\n",
      "Indexing rows in table: Radio_Stations\n",
      "Indexing rows in table: Renaissance_Discography\n",
      "Indexing rows in table: Schools_in_Ohio\n",
      "Indexing rows in table: Temperature_and_Precipitation\n",
      "Indexing rows in table: Voter_Party_Statistics\n",
      "Indexing rows in table: Voter_Registration_Statistics\n",
      "Indexing rows in table: Yamato_District_Area_Population\n",
      "Indexing rows in table: Yearly_Deaths_and_Accidents\n"
     ]
    }
   ],
   "source": [
    "from llama_index.core import VectorStoreIndex, load_index_from_storage\n",
    "from sqlalchemy import text\n",
    "from llama_index.core.schema import TextNode\n",
    "from llama_index.core import StorageContext\n",
    "import os\n",
    "from pathlib import Path\n",
    "from typing import Dict\n",
    "\n",
    "\n",
    "def index_all_tables(\n",
    "    sql_database: SQLDatabase, table_index_dir: str = \"table_index_dir\"\n",
    ") -> Dict[str, VectorStoreIndex]:\n",
    "    \"\"\"Index all tables.\"\"\"\n",
    "    if not Path(table_index_dir).exists():\n",
    "        os.makedirs(table_index_dir)\n",
    "\n",
    "    vector_index_dict = {}\n",
    "    engine = sql_database.engine\n",
    "    for table_name in sql_database.get_usable_table_names():\n",
    "        print(f\"Indexing rows in table: {table_name}\")\n",
    "        if not os.path.exists(f\"{table_index_dir}/{table_name}\"):\n",
    "            # get all rows from table\n",
    "            with engine.connect() as conn:\n",
    "                cursor = conn.execute(text(f'SELECT * FROM \"{table_name}\"'))\n",
    "                result = cursor.fetchall()\n",
    "                row_tups = []\n",
    "                for row in result:\n",
    "                    row_tups.append(tuple(row))\n",
    "\n",
    "            # index each row, put into vector store index\n",
    "            nodes = [TextNode(text=str(t)) for t in row_tups]\n",
    "\n",
    "            # put into vector store index (use OpenAIEmbeddings by default)\n",
    "            index = VectorStoreIndex(nodes)\n",
    "\n",
    "            # save index\n",
    "            index.set_index_id(\"vector_index\")\n",
    "            index.storage_context.persist(f\"{table_index_dir}/{table_name}\")\n",
    "        else:\n",
    "            # rebuild storage context\n",
    "            storage_context = StorageContext.from_defaults(\n",
    "                persist_dir=f\"{table_index_dir}/{table_name}\"\n",
    "            )\n",
    "            # load index\n",
    "            index = load_index_from_storage(\n",
    "                storage_context, index_id=\"vector_index\"\n",
    "            )\n",
    "        vector_index_dict[table_name] = index\n",
    "\n",
    "    return vector_index_dict\n",
    "\n",
    "\n",
    "vector_index_dict = index_all_tables(sql_database)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "701a2781-d728-4ea6-9c6a-f4b2aaf23f3a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('Diddy', 1993, '6')\n"
     ]
    }
   ],
   "source": [
    "test_retriever = vector_index_dict[\"Bad_Boy_Artists\"].as_retriever(\n",
    "    similarity_top_k=1\n",
    ")\n",
    "nodes = test_retriever.retrieve(\"P. Diddy\")\n",
    "print(nodes[0].get_content())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f3c1911-9f94-4a44-a018-f576f74b515a",
   "metadata": {},
   "source": [
    "### Define Expanded Table Parser Component\n",
    "\n",
    "We expand the capability of our `table_parser_component` to not only return the relevant table schemas, but also return relevant rows per table schema.\n",
    "\n",
    "It now takes in both `table_schema_objs` (output of table retriever), but also the original `query_str` which will then be used for vector retrieval of relevant rows."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f3203365-1d0b-4217-853c-8733517a7884",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.retrievers import SQLRetriever\n",
    "from typing import List\n",
    "from llama_index.core.query_pipeline import FnComponent\n",
    "\n",
    "sql_retriever = SQLRetriever(sql_database)\n",
    "\n",
    "\n",
    "def get_table_context_and_rows_str(\n",
    "    query_str: str, table_schema_objs: List[SQLTableSchema]\n",
    "):\n",
    "    \"\"\"Get table context string.\"\"\"\n",
    "    context_strs = []\n",
    "    for table_schema_obj in table_schema_objs:\n",
    "        # first append table info + additional context\n",
    "        table_info = sql_database.get_single_table_info(\n",
    "            table_schema_obj.table_name\n",
    "        )\n",
    "        if table_schema_obj.context_str:\n",
    "            table_opt_context = \" The table description is: \"\n",
    "            table_opt_context += table_schema_obj.context_str\n",
    "            table_info += table_opt_context\n",
    "\n",
    "        # also lookup vector index to return relevant table rows\n",
    "        vector_retriever = vector_index_dict[\n",
    "            table_schema_obj.table_name\n",
    "        ].as_retriever(similarity_top_k=2)\n",
    "        relevant_nodes = vector_retriever.retrieve(query_str)\n",
    "        if len(relevant_nodes) > 0:\n",
    "            table_row_context = \"\\nHere are some relevant example rows (values in the same order as columns above)\\n\"\n",
    "            for node in relevant_nodes:\n",
    "                table_row_context += str(node.get_content()) + \"\\n\"\n",
    "            table_info += table_row_context\n",
    "\n",
    "        context_strs.append(table_info)\n",
    "    return \"\\n\\n\".join(context_strs)\n",
    "\n",
    "\n",
    "table_parser_component = FnComponent(fn=get_table_context_and_rows_str)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "050daa4c-302b-48a6-b888-7ecee30d7058",
   "metadata": {},
   "source": [
    "### Define Expanded Query Pipeline\n",
    "\n",
    "This looks similar to the query pipeline in section 1, but with an upgraded table_parser_component."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "84bcf7eb-9d8d-46b7-8b01-66a6c82ece11",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.query_pipeline import (\n",
    "    QueryPipeline as QP,\n",
    "    Link,\n",
    "    InputComponent,\n",
    "    CustomQueryComponent,\n",
    ")\n",
    "\n",
    "qp = QP(\n",
    "    modules={\n",
    "        \"input\": InputComponent(),\n",
    "        \"table_retriever\": obj_retriever,\n",
    "        \"table_output_parser\": table_parser_component,\n",
    "        \"text2sql_prompt\": text2sql_prompt,\n",
    "        \"text2sql_llm\": llm,\n",
    "        \"sql_output_parser\": sql_parser_component,\n",
    "        \"sql_retriever\": sql_retriever,\n",
    "        \"response_synthesis_prompt\": response_synthesis_prompt,\n",
    "        \"response_synthesis_llm\": llm,\n",
    "    },\n",
    "    verbose=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c7bd7b14-9c5a-40af-ac8d-d435d5c7a19c",
   "metadata": {},
   "outputs": [],
   "source": [
    "qp.add_link(\"input\", \"table_retriever\")\n",
    "qp.add_link(\"input\", \"table_output_parser\", dest_key=\"query_str\")\n",
    "qp.add_link(\n",
    "    \"table_retriever\", \"table_output_parser\", dest_key=\"table_schema_objs\"\n",
    ")\n",
    "qp.add_link(\"input\", \"text2sql_prompt\", dest_key=\"query_str\")\n",
    "qp.add_link(\"table_output_parser\", \"text2sql_prompt\", dest_key=\"schema\")\n",
    "qp.add_chain(\n",
    "    [\"text2sql_prompt\", \"text2sql_llm\", \"sql_output_parser\", \"sql_retriever\"]\n",
    ")\n",
    "qp.add_link(\n",
    "    \"sql_output_parser\", \"response_synthesis_prompt\", dest_key=\"sql_query\"\n",
    ")\n",
    "qp.add_link(\n",
    "    \"sql_retriever\", \"response_synthesis_prompt\", dest_key=\"context_str\"\n",
    ")\n",
    "qp.add_link(\"input\", \"response_synthesis_prompt\", dest_key=\"query_str\")\n",
    "qp.add_link(\"response_synthesis_prompt\", \"response_synthesis_llm\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0cc3fbb5-ba53-472f-a9c9-6070980734a9",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pyvis.network import Network\n",
    "\n",
    "net = Network(notebook=True, cdn_resources=\"in_line\", directed=True)\n",
    "net.from_nx(qp.dag)\n",
    "net.show(\"text2sql_dag.html\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "33c79a4c-3810-4093-95f8-f8445cad3a5e",
   "metadata": {},
   "source": [
    "### Run Some Queries\n",
    "\n",
    "We can now ask about relevant entries even if it doesn't exactly match the entry in the database."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "248a4ee5-29ed-4d7c-becb-51fddb5f4849",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1;3;38;2;155;135;227m> Running module input with input: \n",
      "query: What was the year that The Notorious BIG was signed to Bad Boy?\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module table_retriever with input: \n",
      "input: What was the year that The Notorious BIG was signed to Bad Boy?\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module table_output_parser with input: \n",
      "query_str: What was the year that The Notorious BIG was signed to Bad Boy?\n",
      "table_schema_objs: [SQLTableSchema(table_name='Bad_Boy_Artists', context_str='List of artists signed to Bad Boy Records and their album releases'), SQLTableSchema(table_name='Bad_Boy_Artists', context_str='List of artis...\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module text2sql_prompt with input: \n",
      "query_str: What was the year that The Notorious BIG was signed to Bad Boy?\n",
      "schema: Table 'Bad_Boy_Artists' has columns: Act (VARCHAR), Year_signed (INTEGER), _Albums_released_under_Bad_Boy (VARCHAR), and foreign keys: . The table description is: List of artists signed to Bad Boy Rec...\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module text2sql_llm with input: \n",
      "messages: Given an input question, first create a syntactically correct sqlite query to run, then look at the results of the query and return the answer. You can order the results by a relevant column to return...\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module sql_output_parser with input: \n",
      "response: assistant: SELECT Year_signed\n",
      "FROM Bad_Boy_Artists\n",
      "WHERE Act = 'The Notorious B.I.G'\n",
      "SQLResult: 1993\n",
      "Answer: The Notorious BIG was signed to Bad Boy in 1993.\n",
      "\n",
      "\u001b[0mRAW RESPONSE  SELECT Year_signed\n",
      "FROM Bad_Boy_Artists\n",
      "WHERE Act = 'The Notorious B.I.G'\n",
      "SQLResult: 1993\n",
      "Answer: The Notorious BIG was signed to Bad Boy in 1993.\n",
      "\u001b[1;3;38;2;155;135;227m> Running module sql_retriever with input: \n",
      "input: SELECT Year_signed\n",
      "FROM Bad_Boy_Artists\n",
      "WHERE Act = 'The Notorious B.I.G'\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module response_synthesis_prompt with input: \n",
      "query_str: What was the year that The Notorious BIG was signed to Bad Boy?\n",
      "sql_query: SELECT Year_signed\n",
      "FROM Bad_Boy_Artists\n",
      "WHERE Act = 'The Notorious B.I.G'\n",
      "context_str: [NodeWithScore(node=TextNode(id_='23214862-784c-4f2b-b489-39d61ea96580', embedding=None, metadata={}, excluded_embed_metadata_keys=[], excluded_llm_metadata_keys=[], relationships={}, hash='c336a1cbf9...\n",
      "\n",
      "\u001b[0m\u001b[1;3;38;2;155;135;227m> Running module response_synthesis_llm with input: \n",
      "messages: Given an input question, synthesize a response from the query results.\n",
      "Query: What was the year that The Notorious BIG was signed to Bad Boy?\n",
      "SQL: SELECT Year_signed\n",
      "FROM Bad_Boy_Artists\n",
      "WHERE Act = '...\n",
      "\n",
      "\u001b[0massistant: The Notorious BIG was signed to Bad Boy in 1993.\n"
     ]
    }
   ],
   "source": [
    "response = qp.run(\n",
    "    query=\"What was the year that The Notorious BIG was signed to Bad Boy?\"\n",
    ")\n",
    "print(str(response))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "llama_index_v2",
   "language": "python",
   "name": "llama_index_v2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
